from fastapi import APIRouter, Query, UploadFile
from tortoise.expressions import Q
from fastapi.responses import JSONResponse
from tortoise.transactions import in_transaction

from app.controllers.marketing.draw_rule import draw_rule_controller
from app.controllers.marketing.draw import draw_controller
from app.controllers.marketing.integral import integral_controller
from app.models import CustomerUser, DrawlRole, CouponsRole, Goods, OrdersList
from app.schemas.base import Success, SuccessExtra, Fail
from app.core.dependency import DependCustomerAuth
from app.core.ctx import CTX_USER_ID
from app.schemas.marketing import IntegralCreate

mini_draw_router = APIRouter()
model_name = "抽奖"


@mini_draw_router.get("/list", summary=f"转盘奖品列表", dependencies=[DependCustomerAuth])
async def get_draws(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
):
    user_id = CTX_USER_ID.get()
    q = Q()
    total, data = await draw_rule_controller.do_list(page=page, page_size=page_size, search=q)
    for item in data:
        item["img"] = item["cover"]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@mini_draw_router.get("/draw_list", summary=f"中奖记录", dependencies=[DependCustomerAuth])
async def get_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
):
    user_id = CTX_USER_ID.get()
    q = Q()
    if user_id > 0:
        q &= Q(user_id=user_id)
    total, data = await draw_controller.do_list(page=page, page_size=page_size, search=q)

    draw_rules = await DrawlRole.all()
    draw_dict = {draw.id: draw for draw in draw_rules}

    for item in data:
        draw = draw_dict[item['draw_id']]
        item['draw_goods'] = draw.name
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@mini_draw_router.get("/draw", summary=f"抽奖", dependencies=[DependCustomerAuth])
async def do_draw(
        order_id: int = Query(0, description="订单编号"),
):
    user_id = CTX_USER_ID.get()
    async with in_transaction() as transaction:
        try:

            price = await integral_controller.do_user_info(user_id=user_id)
            if price >= 9:
                prize = await draw_controller.do_draw(user_id=user_id, order_id=order_id)
                obj_in = IntegralCreate(
                    user_id=user_id,
                    price=9,
                    direction=2,
                    type=1,
                    type_id=0,
                    remark='抽奖积分扣除',
                )

                price = await integral_controller.do_create(obj_in)
                data = {
                    "id": prize["id"],
                    "name": prize["name"],
                    "integral": price,
                }
                return SuccessExtra(data=data)
            else:
                return JSONResponse(content={"code": 400, "msg": "积分不足"}, status_code=200)
        except Exception as e:
            return {"msg": f"错误{e}"}
